package com.itheima.exerciseTest.method40_49.method49;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.ConnectException;
import java.net.Socket;
import java.util.Scanner;

// 客户端
public class ClientDemo {
    private static final Logger LOGGER = LoggerFactory.getLogger(ClientDemo.class);
    private static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        Socket s = null;
        try {
            s = new Socket("192.168.80.1", 10011);
        } catch (ConnectException e) {
            LOGGER.info("与服务器连接失败" + e);
        }

        // 接收服务器响应
        BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String str = br.readLine();
        System.out.println(str);

        // 获得上传文件地址
        // File file = getfile(); // "D:\\aheima\\模拟考试\\考试\\试题B\\test.txt"


        // 获得上传文件编码方式
        // String format = setCodedFormat();


        // 给服务器发送文本文件
        // 读取本地文件
//        BufferedReader br2 = new BufferedReader(new InputStreamReader(new FileInputStream("D:\\aheima\\模拟考试\\考试\\试题B\\test.txt")));
//        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
//        String str2;
//        while ((str2 = br2.readLine()) != null) {
//            bw.write(str2);
//            bw.newLine();
//            bw.flush();
//        }
//        s.shutdownOutput();
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\aheima\\模拟考试\\考试\\试题B\\test.txt"));
        BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
        byte[] bytes = new byte[1024];
        int len;
        while ((len = bis.read(bytes)) != -1) {
            bos.write(bytes, 0, len);
        }
        s.shutdownOutput();

//        // 接收服务器响应
        str = br.readLine();
        System.out.println(str);

        // br2.close();
        s.close();
    }

    // 获取文件地址
    public static File getfile() {
        File file;
        while (true) {
            System.out.println("请输入要上传的文件地址：");
            String str = sc.nextLine().trim();
            file = new File(str);
            if (file.isFile() && file.exists()) {
                System.out.println("文件名格式正确且存在支持上传");
                break;
            } else if (!file.isFile()) {
                System.out.println("文件格式不正确，请重新输入");
            } else if (!file.exists()) {
                System.out.println("文件不存在，请重新输入");
            }
        }
        return file;
    }

    // 设置复制时的编码格式
    public static String setCodedFormat() {
        String str;
        while (true) {
            System.out.println("请输入文件的编码方式：（目前只支持UTF-8 和 GBK编码方式）");
            str = sc.nextLine().trim();
            if ("utf-8".equals(str) || "UTF-8".equals(str) || "gbk".equals(str) || "GBK".equals(str)) {
                break;
            }
            System.out.println("编码方式不正确，请重新输入");
        }
        return str;
    }

}
